package com.maishi.programmer.jainzhioffer;

import java.util.ArrayList;
import java.util.Queue;
import java.util.Stack;

/**
 * Created by brossdong on 2018/4/23.
 * 将一个字符串转换成一个整数，
 * 要求不能使用字符串转换整数的库函数。
 * 数值为0或者字符串不是一个合法的数值则返回0
 */
public class TestProblem67 {

    public static int StrToInt(String str) {

        /*if (str == null || str.length() < 1 || str == " ") return 0;
        char[] chars = str.toCharArray();
        ArrayList list = new ArrayList();
        for (int i = 0;i < chars.length;i++) {
            //非法判断
            if (chars[0] == '+' || chars[0] == '-' || chars[i] <= '9' && chars[i] >= '0') {
                if (chars[0] == '+') {
                    chars[0] = '0';
                    int num = chars[i] - '0';
                    list.add(num);
                }
                if (chars[0] == '-') {
                    chars[0] = '0';
                    int num = chars[i] - '0';
                    list.add("-" + num);
                }
                int num = chars[i] - '0';
                list.add(num);
            } else {
                return 0;
            }
        }
        Object[] array = list.toArray();
        String strs = "";
        for (int i = 0;i < array.length;i++) {
            strs += array[i];
        }
        return Integer.valueOf(strs);*/
        if (str.equals("") || str.length() == 0)
            return 0;
        char[] a = str.toCharArray();
        int fuhao = 0;
        if (a[0] == '-')
            fuhao = 1;
        int sum = 0;
        for (int i = fuhao; i < a.length; i++)
        {
            if (a[i] == '+')
                continue;
            if (a[i] < 48 || a[i] > 57)
                return 0;
            sum = sum * 10 + a[i] - 48;
        }
        return fuhao == 0 ? sum : sum * -1;

    }

    public static void main(String[] args) {
        int i = StrToInt("+1234");
        System.out.println(i);
    }

}
